<template>
  <el-dialog
    :title="add === 'add' ? '新增人员' : '编辑人员'"
    :visible.sync="dialogVisible"
    :before-close="dialogV"
    width="40%"
  >
    <el-form ref="form" :model="form" :rules="rules">
      <el-form-item label="人员名称:" label-width="120px" prop="userName">
        <el-input
          v-model="form.userName"
          placeholder="请输入"
          class="inputWidth"
          maxlength="5"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="角色:" label-width="120px" prop="roleId">
        <el-select
          v-model="form.roleId"
          placeholder="请选择"
          class="inputWidth"
        >
          <el-option
            v-for="item in roleList"
            :key="item.roleId"
            :label="item.roleName"
            :value="item.roleId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="联系电话:" label-width="120px" prop="mobile">
        <el-input
          v-model="form.mobile"
          placeholder="请输入"
          class="inputWidth"
          maxlength="11"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="负责区域:" label-width="120px" prop="regionId">
        <el-select
          v-model="form.regionId"
          placeholder="请选择"
          class="inputWidth"
        >
          <el-option
            v-for="item in regionList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="头像:" label-width="120px" prop="image">
        <el-upload
          v-model="form.image"
          class="avatar-uploader"
          action="http://likede2-java.itheima.net/image/"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :http-request="uploadImage"
        >
          <img v-if="form.image" :src="form.image" class="avatar" />
          <i v-else class="el-icon-upload2"></i>
        </el-upload>
        <div class="imgType">支持扩展名:jpg、png、文件不得大于100kb</div>
      </el-form-item>
      <el-form-item label="状态:" label-width="120px">
        <el-checkbox v-model="form.status">是否启用</el-checkbox>
      </el-form-item>

      <el-form-item class="btn">
        <el-button type="primary" class="del" @click="dialogV">取消</el-button>
        <el-button class="add" @click="addBtn">确认</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import COS from 'cos-js-sdk-v5'
import { roleList, regionList, addUser, editUser, addImg } from '@/api/renyuan'
export default {
  name: 'renyuanAdd',
  props: ['form', 'add'],
  data () {
    return {
      dialogVisible: false,
      imageUrl: null,
      roleList: [],
      regionList: [],
      rules: {
        userName: [
          { required: true, message: '请输入人员名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
        mobile: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          {
            pattern:
              /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
            min: 11,
            max: 11,
            message: '请输入正确电话号码',
            trigger: 'blur'
          }
        ],
        regionId: [
          { required: true, message: '请选择区域', trigger: 'change' }
        ],
        image: [{ required: true, message: '请上传头像', trigger: 'submit' }]
      }
    }
  },
  async created () {
    this.roleList = await roleList()
    this.regionList = (
      await regionList({ pageIndex: 1, pageSize: 10000 })
    ).currentPageRecords
  },
  methods: {
    dialogH () {
      this.dialogVisible = true
    },
    dialogV () {
      this.dialogVisible = false
      this.$refs.form.resetFields()
    },
    async handleAvatarSuccess (res, file) {
      console.log(file)
      // console.log(await addImg({ file: file.name.toString(2) }))
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || 'image/png'
      const isLt100kb = file.size / 1024 <= 100
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt100kb) {
        this.$message.error('上传头像图片大小不能超过 100kb!')
      }
      return isJPG && isLt100kb
    },
    // 选择图片上传
    uploadImage (params) {
      const cos = new COS({
        SecretId: 'AKIDOgkU0IMBrJWXLvISZUBestgFj9ML6cu4',
        SecretKey: 'yiGclhQwFMGxRinfNrjQtAxXzEG8nFUV'
      }) // 完成cos对象的初始化
      cos.putObject(
        {
          Bucket: 'likede-img-1318639081', // 存储桶名称
          Region: 'ap-nanjing', // 地域名称
          Key: params.file.name, // 文件名称
          StorageClass: 'STANDARD', // 固定值
          Body: params.file // 文件对象
        },
        (err, data) => {
          if (data.statusCode === 200 && data.Location) {
            // 拿到了腾讯云返回的地址
            // 通过input自定义事件将地址传出去
            console.log('http://' + data.Location)
            this.form.image = 'http://' + data.Location
            // this.$emit('update:form.image', 'http://' + data.Location) // 将地址返回了
          } else {
            this.$message.error(err.Message) // 上传失败提示消息
          }
        }
      )
    },
    addBtn () {
      this.$refs.form.validate(valid => {
        if (valid) {
          console.log(this.form)
          if (!this.form.id) {
            addUser(this.form)
              .then(res => {
                console.log(res)
                if (res) {
                  this.$message.success('添加成功')
                  this.dialogV()
                  this.$refs.form.resetFields()
                  this.$emit('reset')
                } else {
                  this.$message.error(res.msg)
                }
              })
              .catch(err => err)
          } else {
            editUser(this.form)
              .then(res => {
                if (res) {
                  this.$message.success('修改成功')
                  this.dialogV()
                  this.$refs.form.resetFields()
                  this.$emit('reset')
                } else {
                  this.$message.error(res.msg)
                }
              })
              .catch(err => err)
          }
        } else {
          this.$Message.error('*号为必填项!')
        }
      })
    }
  },
  watch: {
    form: {
      deep: true,
      handler (val, old) {
        if (old.regionId) {
          this.form.regionName = this.regionList.find(
            item => item.id === this.form.regionId
          ).name
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader .el-icon-upload2 {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background-color: #f3f6fb;
}
.avatar-uploader .el-icon-upload2:hover {
  border-color: #409eff;
}
.el-icon-upload2 {
  font-size: 16px;
  color: #8c939d;
  width: 84px;
  height: 84px;
  line-height: 84px;
  text-align: center;
}
.avatar {
  width: 84px;
  height: 85px;
  display: block;
}
.imgType {
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica Neue,
    Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif;
  box-sizing: border-box;
  margin-top: 7px;
  font-size: 14px;
  color: #bac0cd;
  line-height: 1.15;
}
.btn {
  text-align: center;
}
.del {
  background-color: #fbf4f0 !important;
  border: none;
  color: #655b56 !important;
}
.add {
  background: linear-gradient(135deg, #ff9743, #ff5e20) !important;
  border: none;
  margin-left: 34px !important;
  color: #fff;
}
.inputWidth {
  width: 400px;
}
</style>
